home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 7: Sunsite / Linux Cubed Series 7 - Sunsite Vol 1.iso / system / shells / kiss-0.11 / kiss-0 / kiss / src / dogrep.c < prev    next >
C/C++ Source or Header  |  1995-03-23  |  2KB  |  90 lines

  1. #include "kiss.h"
  2.  
  3. static int match (FILE *inf, regex_t *regp, GrepFlags fl, char *filename)
  4. {
  5.     char
  6.     buf [FILENAMELEN];
  7.     int
  8.     nmatches = 0,
  9.     found;
  10.  
  11.     while (1)
  12.     {
  13.     if (! (fgets (buf, FILENAMELEN - 1, inf)) )
  14.         break;
  15.     found = ! regexec (regp, buf, 0, NULL, 0);
  16.     if ( (found && !fl.reverse) || (!found && fl.reverse) )
  17.     {
  18.         nmatches++;
  19.         if (filename)
  20.         printf ("%s: ", filename);
  21.         printf ("%s", buf);
  22.     }
  23.     }
  24.     return (nmatches);
  25. }
  26.  
  27. int dogrep (Stringstack s)
  28. {
  29.     GrepFlags
  30.     fl = { 0, 0 };
  31.     register int
  32.     i,
  33.     ret = 0,
  34.     nout = 0,
  35.     opt,
  36.     regflags = REG_EXTENDED | REG_NEWLINE | REG_NOSUB;
  37.     regex_t
  38.     regex;
  39.     FILE
  40.     *inf;
  41.  
  42.     while ( (opt = getopt (s.nstr, s.str, "hiv")) != -1 )
  43.     switch (opt)
  44.     {
  45.         case 'i':
  46.         fl.ignorecase = 1;
  47.         regflags |= REG_ICASE;
  48.         break;
  49.         case 'v':
  50.         fl.reverse = 1;
  51.         break;
  52.         case 'h':
  53.         default:
  54.         error ("Bad commandline.\n"
  55.                "Usage: %s [-iv] expression [file(s)]\n"
  56.                "Where:\n"
  57.                "    -i: ignore case when matching\n"
  58.                "    -v: show non-matching lines of information\n"
  59.                "    file(s): files to scan, stdin when absent\n"
  60.                , progname);
  61.     }
  62.     if (s.nstr < 2)
  63.     error ("needs an expression to match");
  64.  
  65.     if (regcomp (®ex, s.str [optind], regflags))
  66.     error ("bad expression \"%s\"", s.str [optind]);
  67.  
  68.     if (s.nstr > optind + 1)
  69.     for (i = optind + 1; i < s.nstr; i++)
  70.     {
  71.         if (! (inf = fopen (s.str [i], "r")) )
  72.         ret += warning ("cannot open \"%s\" for reading", s.str [i]);
  73.         else
  74.         {
  75.         nout += match (inf, ®ex, fl, s.str [i]);
  76.         fclose (inf);
  77.         }
  78.     }
  79.     else
  80.     nout = match (stdin, ®ex, fl, NULL);
  81.  
  82.     regfree (®ex);
  83.  
  84.     if (! nout)
  85.     ret++;
  86.  
  87.     return (ret);
  88. }
  89.     
  90.